<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Product;
use App\Models\Brand;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;

class ProductController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Product(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('product_name');
            $grid->column('product_model');
            $grid->column('brand_id')->display(function ($item) {
                return \App\Models\Brand::find($item)->brands_name;
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Product(), function (Show $show) {
            $show->field('id');
            $show->field('product_name');
            $show->field('product_model');
            $show->field('brand_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Product(), function (Form $form) {
            $form->display('id');
            $form->text('product_name');
            $form->text('product_model');
            $form->select('brand_id')->options(function ($id) {

                $brand = \App\Models\Brand::find($id);
                if ($brand) {
                    return [$brand->id => $brand->brands_name];
                }

            })->ajax('brands/get');

            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    // 加载可用商品
    public function getProducts(Request $request)
    {
        $q = $request->get('q');
        return \App\Models\Product::where('brand_id', $q)
            ->select('id', 'product_name as text')
            ->get();
    }
}
